aboutsummaryrefslogtreecommitdiffstats
path: root/packages/web/app/api/v1/bookmarks/[bookmarkId]/route.ts
blob: 0963cf946aa546c2dfeb52d92c79e21b5faa2eb4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { authOptions } from "@/lib/auth";
import { deleteBookmark, updateBookmark } from "@/lib/services/bookmarks";
import { ZBookmark, zUpdateBookmarksRequestSchema } from "@/lib/types/api/bookmarks";
import { Prisma } from "@remember/db";

import { getServerSession } from "next-auth";
import { NextRequest, NextResponse } from "next/server";

export async function PATCH(
  request: NextRequest,
  { params }: { params: { bookmarkId: string } },
) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return new Response(null, { status: 401 });
  }

  const updateJson = await request.json();
  const update = zUpdateBookmarksRequestSchema.safeParse(updateJson);
  if (!update.success) {
    return new Response(null, { status: 400 });
  }

  try {
    const bookmark: ZBookmark = await updateBookmark(
      params.bookmarkId,
      session.user.id,
      update.data,
    );
    return NextResponse.json(bookmark);
  } catch (e: unknown) {
    if (
      e instanceof Prisma.PrismaClientKnownRequestError &&
      e.code === "P2025" // RecordNotFound
    ) {
      return new Response(null, { status: 404 });
    } else {
      throw e;
    }
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: { bookmarkId: string } },
) {
  // TODO: We probably should be using an API key here instead of the session;
  const session = await getServerSession(authOptions);
  if (!session) {
    return new Response(null, { status: 401 });
  }

  try {
    await deleteBookmark(params.bookmarkId, session.user.id);
  } catch (e: unknown) {
    if (
      e instanceof Prisma.PrismaClientKnownRequestError &&
      e.code === "P2025" // RecordNotFound
    ) {
      return new Response(null, { status: 404 });
    } else {
      throw e;
    }
  }

  return new Response(null, { status: 204 });
}